package edu.cmu.mixer.wrapup.proxy;

public class ProxyServlet  extends javax.servlet.http.HttpServlet {
  public void doGet(javax.servlet.http.HttpServletRequest req,
                    javax.servlet.http.HttpServletResponse resp) throws java.io.IOException {
    this.doPost(req, resp);
  }

  public static boolean isNonProxied(java.net.URL url) throws Exception {
    java.net.URL url2 = new java.net.URL(url.getProtocol(),
					 url.getHost(),
					 url.getPort(),
					 url.getPath());
				       
    return isNonProxied(url2.toString());
  }

  public static boolean isNonProxied(String url) {
    boolean nonproxied = false;
    nonproxied = nonproxied || url.endsWith(".gif");
    nonproxied = nonproxied || isNonProxied(url, System.getProperty("com.google.appengine.application.id", "localhost"));
    nonproxied = nonproxied || isNonProxied(url, "localhost");
    return nonproxied;
  }
  
  public static boolean isNonProxied(String url, String substring) {
    int ix = url.toString().indexOf(substring);
    if (ix >= 0) {
      if (ix <= 20) {
        return true;
      }
    }
     
    return false;
  }
  
  public void doPost(javax.servlet.http.HttpServletRequest req,
                     javax.servlet.http.HttpServletResponse resp) throws java.io.IOException {

    org.json.JSONObject json = new org.json.JSONObject();
    try {
      
      json.putOpt("now", new java.util.Date().toString());
      json.putOpt("requestURL", req.getRequestURL().toString());
      json.putOpt("requestURI", req.getRequestURI().toString());
      json.putOpt("serverName", req.getServerName().toString());
      json.putOpt("context", getServletContext().getContextPath().toString());
      json.putOpt("serverInfo", getServletContext().getServerInfo().toString());
      json.putOpt("realPath", getServletContext().getRealPath(json.optString("requestURI", "/")).toString());
      json.putOpt("appid", System.getProperty("com.google.appengine.application.id"));
      
      try {
        java.net.URL url = new java.net.URL(req.getRequestURL().toString());

        if (! isNonProxied(url)) {
          System.err.println("PROXYING: " + url.toString());
          java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
          //conn.setDoOutput(true);
          conn.setRequestMethod("GET");
          for (java.util.Enumeration<String> e = req.getHeaderNames() ; e.hasMoreElements() ;) {
            String name = e.nextElement();
            conn.setRequestProperty(name, req.getHeader(name));
          }
          
          System.err.println("CTYPE: " + conn.getContentType());
          resp.setContentType(conn.getContentType());
          
          java.io.InputStream in = conn.getInputStream();
          int count;
          byte[] buffer = new byte[8192];
          while ((count = in.read(buffer)) > 0) {
            resp.getOutputStream().write(buffer, 0, count);
          }

          System.err.println("JSON: " + json.toString(2));
        
          return;
        }  
      } catch (Exception ex1) {
        ex1.printStackTrace(System.err);
      }
      
      resp.setContentType("application/json");
      resp.getWriter().write(json.toString(2));
      resp.getWriter().write("\n");
    } catch (Exception ex) {
      ex.printStackTrace(System.err);
      resp.setContentType("text/plain");
      ex.printStackTrace(resp.getWriter());
    }
    
  }

}
